import Taro from "@tarojs/taro";

import { FILEUPLOAD_STATUS_TYPES } from "../constants/common";

import Base64 from "@/lib/Base64.js";
import "@/lib/hmac";
import "@/lib/sha1";
import Crypto from "@/lib/crypto.js";

const aliyunoss = {
  uploadImageUrl: "https://mmts.oss-cn-shanghai.aliyuncs.com/", //默认存在根目录，可根据需求改  bucket + region + .aliyuncs.com
  AccessKeySecret: "JRhU8o9Gjur4XsXmKWjcORAmnaJWcw",
  OSSAccessKeyId: "LTAIl8X8cE1yB3QF",
  timeout: 87600, //这个是上传文件时Policy的失效时间
  dir: "images/weixin/",
};
let env = aliyunoss;

const uploadFile = function (params) {
  if (!params.filePath) {
    Taro.showModal({
      title: "图片错误",
      content: "请重试",
      showCancel: false,
    });
    return;
  }
  try {
    const curFilename = params.filePath.replace("http://tmp/", "");
    const aliyunFileKey = env.dir + curFilename;
    const aliyunServerURL = env.uploadImageUrl;
    const accessid = env.OSSAccessKeyId;
    const policyBase64 = getPolicyBase64();
    const signature = getSignature(policyBase64);
    let imageUrl = `${aliyunServerURL}${aliyunFileKey}`;
    Taro.uploadFile({
      url: aliyunServerURL,
      filePath: params.filePath,
      name: "file",
      formData: {
        key: aliyunFileKey,
        policy: policyBase64,
        OSSAccessKeyId: accessid,
        signature: signature,
        success_action_status: "200",
      },
      success: function (res) {
        // console.log("success", res);
        if (res.statusCode != 200) {
          if (params.fail) {
            params.fail(res);
          }
          return;
        }
        if (params.success) {
          params.success({
            url: imageUrl,
            name: aliyunFileKey,
            modelType: params.modelType,
            keyName: aliyunFileKey,
            buketDomain: aliyunServerURL,
            status: FILEUPLOAD_STATUS_TYPES.N,
          });
        }
      },
      fail: function (err) {
        console.log("fail", err);
        err.wxaddinfo = aliyunServerURL;
        if (params.fail) {
          params.fail(err);
        }
      },
    });
  } catch (error) {
    console.log("上传错误,", error);
  }
};

const getPolicyBase64 = function () {
  let date = new Date();

  date.setHours(date.getHours() + env.timeout);

  let srcT = date.toISOString();

  const policyText = {
    expiration: srcT, //设置该Policy的失效时间
    conditions: [
      ["content-length-range", 0, 5 * 1024 * 1024], // 设置上传文件的大小限制,5mb
    ],
  };

  const policyBase64 = Base64.encode(JSON.stringify(policyText));

  return policyBase64;
};

const getSignature = function (policyBase64) {
  const accesskey = env.AccessKeySecret;
  // console.log(accesskey)

  const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
    asBytes: true,
  });

  const signature = Crypto.util.bytesToBase64(bytes);

  return signature;
};

export default uploadFile;
